import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from './langs'
import ElementLocale from 'element-ui/lib/locale'
import { getFullLanguage } from '@/i18n/utils'

Vue.use(VueI18n)

// const currency = 'CNY'
// if (!localStorage.lang) {
//   localStorage.setItem('lang', 'zh-CN')
// }
// else {
//   currency = {
//     'en': 'US',
//     'zh-CN': 'CNY'
//   }[localStorage.lang] || 'CNY'
// }

const localeMessages = localStorage.getItem('localeMessages')
const localeLang = localStorage.getItem('lang')

const hasCacheLang = !!(localeLang && localeMessages) // 是否有缓存的语言

const localeMessagesObj = hasCacheLang ? JSON.parse(localeMessages) : null

const cacheMessages = {}
// 默认载入的语言包，如果当前是中文，只载入中文，如果当前不是中文，载入中文和缓存的语言包
if (hasCacheLang) {
  cacheMessages[localeLang] = getFullLanguage(localeLang, localeMessagesObj)
  if (localeLang !== 'zh-CN') {
    cacheMessages['zh-CN'] = messages['zh-CN']
  } else {
    cacheMessages['zh-CN'] = {
      ...messages['zh-CN'],
      ...cacheMessages['zh-CN']
    }
  }
}

const i18n = new VueI18n({
  locale: localeLang || 'zh-CN',
  fallbackLocale: 'zh-CN',
  silentTranslationWarn: true,
  messages: hasCacheLang ? cacheMessages : messages
  // numberFormats: {
  //   'en': {
  //     currency: { // 添加 $
  //       style: 'currency', currency
  //     }
  //   },
  //   'zh-CN': {
  //     currency: { // 添加 ￥
  //       style: 'currency', currency
  //     }
  //   }
  // }
})
ElementLocale.i18n((key, value) => {
  return i18n.t(key, value)
})
export default i18n
